import axios from 'axios';
import Vue from 'vue';
import store from '@/store/index';
import router from '@/router';

let loading = null;
// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000,
});
// 过滤请求
service.interceptors.request.use((config) => {
  // store.state.defaultAccountInfo.loginTime
  // 获取当前时间戳
  const currentTime = new Date().getTime();
  // 获取登录时间戳
  const { loginTime } = store.state.defaultAccountInfo;
  if (currentTime - loginTime > 7200000) {
    // 判断当前时间戳与登录时间戳的差值是否大于2小时
    store.commit('resetToken');
    // 跳转到登录页面
    router.push('/login');
  }

  if (!loading) {
    loading = Vue.prototype.$loading({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)',
    });
  }
  return config;
});
// 过滤响应
service.interceptors.response.use((result) => {
  if (loading) {
    loading.close();
    loading = null;
  }
  return result;
});

export default service;
